package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author: 陈安
 * @Date: 2020/12/10$ 19:33$
 * @Description: $todo$
 * @Version 1.0
 */
@Service
public class EsManagerServiceImpl implements EsManagerService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ESManagerMapper esManagerMapper;

    //创建索引库结果
    @Override
    public void createIndexAndMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);

    }

    //导入全部数据到ES索引库
    @Override
    public void importAll() {
        //查询sku集合
        List<Sku> all = skuFeign.findListBySpuId("all");
        if (all == null && all.size() <= 0) {
            throw new RuntimeException("当前还没有商品");
        }
        //将数据格式转化为json格式的字符串
        String s = JSON.toJSONString(all);
        //将json转化成索引库对象
        List<SkuInfo> skuInfos = JSON.parseArray(s, SkuInfo.class);
        //遍历
        for (SkuInfo skuInfo : skuInfos) {
            //将规格json转化成map,因为数据库存的格式要求
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        esManagerMapper.saveAll(skuInfos);

    }

    //根据spuid查询到skulist,导入数据到ES索引库
    @Override
    public void importDataToESBySpuId(String spuId) {
        List<Sku> listBySpuId = skuFeign.findListBySpuId(spuId);

        if(listBySpuId==null && listBySpuId.size()<=0){
            throw  new RuntimeException("没有这个商品,所以无法导入索引库");
        }

        //将集合转化为json
        String s = JSON.toJSONString(listBySpuId);
        //将json转化为我们需要的skuinfo
        List<SkuInfo> skuInfos = JSON.parseArray(s, SkuInfo.class);
        //在把我们的规格信息转化为我们的map
        for (SkuInfo skuInfo : skuInfos) {
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }

        //添加到索引库里面
       esManagerMapper.saveAll(skuInfos);

    }

    @Override
    public void delSkuListBySpuId(String spuId) {
        List<Sku> listBySpuId = skuFeign.findListBySpuId(spuId);
        if(listBySpuId==null && listBySpuId.size()<=0){
            throw new RuntimeException("没有数据");
        }
        for (Sku sku : listBySpuId) {
            //根据sku的id去删除对应的数据
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
